package cn.codingjc.peekaboo.application.config.repeat;

import cn.codingjc.peekaboo.domain.common.constant.CommonConstant;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @auth: coding_jc
 * @date: 2023/5/12 10:30
 * @desc: 构造RepeatRequestWrapper时IO流读取出数据放入body数组中
 */
public class RepeatRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public RepeatRequestWrapper(HttpServletRequest request, HttpServletResponse response) throws IOException {
        super(request);
        request.setCharacterEncoding(CommonConstant.UTF_8);
        response.setCharacterEncoding(CommonConstant.UTF_8);
        this.body = request.getReader().readLine().getBytes(CommonConstant.UTF_8);
    }

    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    public ServletInputStream getInputStream() throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int available() throws IOException {
                return body.length;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }


}
